package com.night.icm.service.business.service;

import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.night.icm.common.exception.NoSuchDataException;
import com.night.icm.common.jpa.PageHelper;
import com.night.icm.common.service.PageDataUtil;
import com.night.icm.common.utils.PageDataDTO;
import com.night.icm.model.business.NotificationInformationDTO;
import com.night.icm.persistence.business.entity.NotificationInformation;
import com.night.icm.persistence.business.entity.SystemFile;
import com.night.icm.persistence.business.reporsitory.NotificationInformationRepository;
import com.night.icm.persistence.business.reporsitory.SystemFileRepository;
import com.night.icm.service.business.mapper.NotificationInformationMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * NotificationInformationServiceImpl
 *
 * @author Liao ZhiYong
 * @date 2020/4/1
 */
@Service
public class NotificationInformationServiceImpl implements NotificationInformationService {

    private final NotificationInformationRepository notificationInformationRepository;
    private final NotificationInformationMapper notificationInformationMapper;
    private final SystemFileRepository systemFileRepository;

    @Autowired
    public NotificationInformationServiceImpl(NotificationInformationRepository notificationInformationRepository, NotificationInformationMapper notificationInformationMapper, SystemFileRepository systemFileRepository) {
        this.notificationInformationRepository = notificationInformationRepository;
        this.notificationInformationMapper = notificationInformationMapper;
        this.systemFileRepository = systemFileRepository;
    }

    /**
     * 分页查找通知信息
     *
     * @param page         页号，从0开始
     * @param size         每页记录条数
     * @param sort         排序字段，例如：字段1,asc,字段2,desc
     * @param title        通知标题
     * @param type         通知类型
     * @param receiverName 通知对象
     * @return 通知信息
     */
    @Override
    public PageDataDTO<NotificationInformationDTO> findOnePage(int page, int size, String sort, String title, String type, String receiverName) {
        PredicateBuilder<NotificationInformation> pb = Specifications.<NotificationInformation>and()
                .like(StringUtils.isNotBlank(title), "title", "%" + title + "%")
                .like(StringUtils.isNotBlank(type), "type", "%" + type + "%")
                .like(StringUtils.isNotBlank(receiverName), "receiverName", "%" + receiverName + "%");
        Page<NotificationInformation> all = this.notificationInformationRepository.findAll(pb.build(), PageHelper.generatePageRequest(page, size, sort));
        List<NotificationInformationDTO> list = this.notificationInformationMapper.toList(all.getContent());
        return PageDataUtil.toPageData(all, list);
    }

    /**
     * 新建通知
     *
     * @param notificationInformationDTO 通知
     * @return 通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public NotificationInformationDTO create(NotificationInformationDTO notificationInformationDTO) {
        NotificationInformation entity = this.notificationInformationMapper.toEntity(notificationInformationDTO);
        NotificationInformation save = this.notificationInformationRepository.save(entity);
        List<String> fileIds = notificationInformationDTO.getFileIds();
        if (null != fileIds && !fileIds.isEmpty()) {
            List<Long> ids = new ArrayList<>();
            fileIds.forEach(id -> ids.add(Long.parseLong(id)));
            List<SystemFile> files = this.systemFileRepository.findAllById(ids);
            save.setFiles(files);
        }
        return this.notificationInformationMapper.toDTO(save);
    }

    /**
     * 根据接收人id查找通知
     *
     * @param receiverId 接收者id
     * @return 通知
     */
    @Override
    public List<NotificationInformationDTO> findByReceiverId(String receiverId) {
        List<NotificationInformation> list = this.notificationInformationRepository.findByReceiverId(receiverId);
        return this.notificationInformationMapper.toList(list);
    }

    /**
     * 通过id查找通知
     *
     * @param id id
     * @return 通知
     */
    @Override
    public NotificationInformationDTO findById(String id) {
        Optional<NotificationInformation> byId = this.notificationInformationRepository.findById(Long.valueOf(id));
        if (!byId.isPresent()) {
            throw new NoSuchDataException(id);
        }
        NotificationInformation notificationInformation = byId.get();
        return this.notificationInformationMapper.toDTO(notificationInformation);
    }

    /**
     * 删除通知
     *
     * @param id id
     * @return 通知
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        this.notificationInformationRepository.deleteById(Long.valueOf(id));
    }

    /**
     * 改变通知状态
     *
     * @param id id
     * @return 状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeStatus(String id) {
        Optional<NotificationInformation> byId = this.notificationInformationRepository.findById(Long.valueOf(id));
        if (!byId.isPresent()) {
            throw new NoSuchDataException(id);
        }
        NotificationInformation notificationInformation = byId.get();
        notificationInformation.setIsConfirm(true);
        this.notificationInformationRepository.save(notificationInformation);
        return true;
    }
}